<template>
    <div class="container">
        <!--大屏头部-->
        <screen-header @navClickCallback="navClickCallback"></screen-header>
        <!-- <a-button type="primary" @click="testalarm">测试报警</a-button> -->
        <!--大屏左侧-->
        <screen-left ref="screenLeft"></screen-left>
        <!--大屏右侧-->
        <screen-right ref="screenRight"></screen-right>
        <!--3D地图-->
        <div class="emap-view">
            <img src="~@/assets/bg.jpg" class="logo" alt="logo"
                style="width: 1200px; height: 800px;" />
            <!-- <emap-label ref="eMapComponent"></emap-label> -->
        </div>
    </div>
</template>

<script>
import screenHeader from './ScreenHeader'
import screenLeft from './ScreenLeft'
import screenRight from './ScreenRight'
import emapLabel from './EmapLabel.vue'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'

export default {
    name: "Home",
    components: { screenHeader, screenLeft, screenRight, emapLabel },
    data() {
        return {
            alarmAudio: '',//报警声音
            websocket: null,
            keepAliveTimer: null,
        }
    },
    // beforeRouteEnter(to,from, next) {
    //   //从后台首页来到此页，需要刷新一下页面之后再进入，否则模型加载速度会减慢
    //   if (from.path ==='/dashboard/analysis'){
    //     document.body.innerHTML = `
    //     <div id="loader-wrapper">
    //       <div id="loader"></div>
    //       <div class="loader-section section-left"></div>
    //       <div class="loader-section section-right"></div>
    //       <div class="load_title">正在加载,请耐心等待
    //       </div>
    //     </div>
    //     `
    //     setTimeout(() => {
    //       next()
    //       location.reload()
    //     })
    //   }else{
    //     next()
    //   }
    // },
    mounted() {
        // this.alarmAudio = new Audio(require('../../../assets/alarm.mp3'))
        // this.alarmAudio.addEventListener("ended", () => {
        //   this.alarmAudio.play()
        // }, false);
        // this.alarmAudio.pause()
        // this.initWebSocket()
        this.keepAliveTimer = window.setInterval(() => {
            // this.successHealthCheck()
        }, 3000)
    },
    destroyed() {
        console.log('3Dhome destroyed')
        // this.alarmAudio.pause()
        // this.alarmAudio.removeEventListener('ended', this.removeAudio(), false)
        console.log('keepAliveTimer定时清除')
        clearInterval(this.keepAliveTimer)
        this.keepAliveTimer = null
        console.log('websocket连接关闭')
        this.websocket ? this.websocket.close() : ''
    },
    methods: {
        removeAudio() {
            console.log('移除audio')
        },
        playAudio() {
            console.log('播放音频')
            this.alarmAudio.play()
        },
        stopAudio() {
            console.log('停止播放')
            this.alarmAudio.pause()
        },
        //顶部模型点选模块，3D地图显示 隐藏对应模型
        navClickCallback(item) {
            let type = item.type
            this.$refs.screenLeft.collapse = true;
            this.$refs.screenRight.collapse = true;
            this.$refs.eMapComponent.onChangeShow(item.selected, type);
        },
        // 初始化 WebSocket
        initWebSocket() {
            console.log('初始化websocket...')
            let userInfo = Vue.ls.get(USER_INFO)
            if (typeof WebSocket != 'undefined') {
                let url = `${window._CONFIG['domianURL']}alarmRecord/websocket/${userInfo.username}`   //这是基本的接口
                let tUrl = url.replace(/http/g, 'ws')                            //这是替换之后的接口
                this.websocket = new WebSocket(tUrl);
                this.websocket.onopen = this.webSocketOnOpen
                this.websocket.onerror = this.webSocketOnError
                this.websocket.onmessage = this.webSocketOnMessage
                this.websocket.onclose = this.webSocketClose
            } else {
                this.$message.warning('您的浏览器不支持WebSocket，请使用Chrome或者Firefox浏览器！')
            }
        },
        successHealthCheck() {
            /*
              readyState 1 尚未建立连接
                         2 连接已建立
                         3 连接正在关闭
                         4 连接已经关闭或不可用
            */
            if (this.websocket.readyState !== 1) {
                console.log('websocket.readyState状态', this.websocket.readyState, '异常')
                //尝试重连
                this.initWebSocket()
            } else {
                // console.log('websocket.readyState状态',this.websocket.readyState,'正常')
            }
        },
        webSocketOnOpen() {
            console.log("WebSocket连接成功");
        },
        webSocketOnError(e) {
            console.log("WebSocket连接错误", e);
            this.initWebSocket()   //尝试重连
        },
        webSocketOnMessage(e) {
            console.log("WebSocket接收到报警消息", e);
            if (e.data) {
                let data = JSON.parse(e.data)
                console.log(data)
                /*
                dataType值：正常报警       -normal(只有正常报警才会显示报警信息）；
                           没有查询到ip设备-noIpDevice；
                           没有查询到报警点-noAlarmPoint
                 */
                if (data.success && data.dataType === 'normal') {
                    this.playAudio()   //播放报警声音
                    let content = `报警点【${data.alarmPointName}】${data.eventTime}发生报警！报警信息:${data.alarmInfo ? data.alarmInfo : '无'}`
                    this.$notification['warning']({
                        key: new Date().getTime(),
                        message: '提示',
                        description: content,
                        duration: 0,
                        onClose: () => {
                            this.stopAudio()
                        }
                    })
                    // if(data.alarmPointType==='PATROL'){
                    //   let param= {
                    //     alarmPointId : data.alarmPointId,
                    //     style : 2,
                    //     alarmInfo:data.alarmInfo
                    //   }
                    //   this.$refs.eMapComponent.beginPatrolAlarm(param)
                    // }else{
                    this.$refs.eMapComponent.beginAlarm(data)
                    // }
                } else {
                    this.$notification['warning']({
                        key: new Date().getTime(),
                        message: '提示',
                        description: data.msg,
                        duration: 5,
                    })
                }
            }
        },
        webSocketClose(e) {
            console.log("WebSocket连接关闭", e);
        },
    }
}
</script>

<style scoped lang="less">
.container {
    width: 100%;
    height: 100vh;
    min-width: 1000px;
    position: relative;
    display: flex;
    flex-direction: column;
    padding: 0;
    margin: 0;
    overflow: hidden;

    .emap-view {
        height: 89%;
        width: 100%;
        margin: auto;
        padding: 0 0 0 150px;
        overflow: hidden;
    }
}
</style>